<template>
	<!-- 工程维保 -->
	<view class="page-jiankong">
		<navBar title="监控调用"  @goBack="goBack"></navBar>
		<u-tabs :list="tabList" :current="currentIndex" @change="changeTab" :scrollable="false" :lineWidth="200" :inactiveStyle="{fontSize:'36rpx'}" :activeStyle="{color:'#2F80ED',fontWeight: '800',fontSize:'36rpx'}" style="background-color: #ffffff;"></u-tabs>
		<!-- 扫码绑定 -->
		<view v-show="currentIndex === 0">
			<view class="viewh">
				<view class="top-select">
					<view class="sel-name" @click="selectConstructionPlan">
						<text class="left-name">施工计划</text>
						<text class="middle-name" style="text-align: right; padding-right: 10px;" :style="{'color': sectionList.length ? '#22204e' : '#c1c1c1'}">{{ sectionList.length ? '已选择' : '请选择每日施工计划' }}</text>
						<u-icon name="arrow-right"></u-icon>
					</view>
					
					<view class="item-list">
						<view v-for="(item, index) in  extractLowestLevelList(sectionList)" :key="index">{{ sectionList[0].name }}   {{ extractLowestLevelList(sectionList)[index].name }}</view>
					</view>
				</view>
				<view style="padding: 40upx 0; background-color: #fff;">
					<view @click="fnScanCode" style="display: flex; align-items: center; justify-content: center; height: 96upx; background: #f5f7fa; border-radius: 4upx; margin: 0 32upx;">
						<image src="/subpackage-enginner/static/scan.png" mode="aspectFill" style="width: 34upx; height: 34upx; margin-right: 18upx;"></image>
						<view style="color: #445469; font-weight: bold;color: #2F80ED;">扫二维码</view>
					</view>
				</view>
			</view>
			<view class="textH">绑定的监控设备</view>
			<scroll-view :scroll-y="true"
				:style="{height:`calc(100vh - ${188 + boxHeight.viewH + 80 + boxHeight.textH}px)`}">
				<view class="item-box" v-for="(item, index) in QRcodes" :key="index">
					<view class="shebei">{{item.deviceName || ''}}</view>
					<view class="box-detail">
						<view class="detail-icon">
							<text>规格型号:{{item.specificationModel || ''}}</text>
							<u-icon @click="delItem(index)" name="trash-fill" color="#66a0e6"></u-icon>
						</view>
						<view class="detail-icon">设备编号:{{item.code || ''}}</view>
						<view class="detail-icon last">所属基地:{{item.stationName || ''}}</view>
					</view>
				</view>
			</scroll-view>
		</view>
		<view class="pop-box">
			<u-modal :show="showModal"  title="识别设备" confirmText="确定并继续" cancelText="取消" 
			:showCancelButton="true" 
			:isShowOther="true"
			confirmColor="#2F80ED"
			cancelColor="#FF6A6A"
			@confirm="closeModel('continue')"
			@cancel="closeModel('cancel')"
			@handelEnd="closeModel('end')">
				<view class="slot-content">
					<view class="info">
						<view>设备名称: {{QRcodeData.deviceName || ''}}</view>
						<view>规格型号: {{QRcodeData.specificationModel || ''}}</view>
						<view>设备编号: {{QRcodeData.code || ''}}</view>
						<view>所属基地: {{QRcodeData.stationName || ''}}</view>
					</view>
					<view v-if="bindData.pmId">
						<u-icon name="info-circle-fill" color="#ffba00" size="25" :customStyle="{marginRight:'20rpx'}"></u-icon>
						<text style="color: #d9001b;" v-if="bindData.type === 'yjqx'">绑定失败!</text>
						<text>该设备已被
							<text style="color: #30b2e4;">[{{`${bindData.lineName}${bindData.branchLineName ? '(' + bindData.branchLineName + ')' : ''}${bindData.type && bindData.type === 'yjqx' ? '' : '、'}${bindData.pmName}`}}]</text>
								绑定,<text>{{ bindData.type && bindData.type === 'yjqx' ? '无法绑定!' : '是否重新绑定到本区间/站点'}}</text>
						</text>
					</view>
				</view>
			</u-modal>
		</view>
		<u-toast ref="uToast"></u-toast>
		<!-- 查看记录 -->
		<view class="" v-show="currentIndex === 1">
			<look-record ref="lookRecordRef"></look-record>
		</view>
		<!-- 按钮 -->
		<view class="footer-button" v-if="currentIndex === 0">
			<view class="button-placeholder"></view>
			<view class="button-group">
				<button @click="determine" :loading="isLoading" class="button-primary">提交</button>
			</view>
		</view>
		
	</view>
</template>

<script>
	import mixins from '@/utils/mixins.js'
	import lookRecord from '@/subpackage-enginner/pages/engineeringMaintenance/jianKong/COMPO/lookRecord.vue'
	import {
		pmBindEqBatchBind,
		getBindInfoByDeviceId,
		specialTasksSetting,
		getWorkingSurface
	} from '@/api/comprehensive/comprehensive.js'
	export default {
		mixins: [mixins],
		components: {
			lookRecord //查看记录组件
		},
		data() {
			return {
				showModal: false,
				formData: {}, //线路选择后的
				pmId: -1,
				tabList: [{
						id: 1,
						name: '扫码绑定'
					},
					{
						id: 2,
						name: '查看记录'
					},
				],
				currentIndex: 0,
				isLoading: false,
				// 几个盒子的高度,计算scroll-view的高度
				boxHeight: {
					navBarH: 40,
					tabsH: 40,
					viewH: 89,
					btnBoxH: 50,
					textH: 22
				},
				// 设备二维码数据
				QRcodes: [], //绑定在页面上的数据
				QRcodeData: {}, //当前扫描的设备数据  假数据JSON.stringify({id:1,deviceName:'监控探头007',siteName:'府村大道01',deviceId:'EQ22111700000806', model:'A型号'})
				bindData: {}, //绑定的数据 
				columns:[[],[]],
				values:[0,0],
				// selectedFaceName:'',
				sectionList: [],
				showArr:{}
			}
		},
		mounted() {
			// 计算scorll-view的高度 , 用100vh减去几个不滚动盒子的高度
			const query = uni.createSelectorQuery().in(this);
			// query.select('.u-navbar .u-navbar--fixed').boundingClientRect(data => {
			// 	this.boxHeight.navBarH = data.height
			// }).exec();
			// query.select('.u-tabs').boundingClientRect(data => {
			// 	this.boxHeight.tabsH = data.height
			// }).exec();
			query.select('.viewh').boundingClientRect(data => {
				this.boxHeight.viewH = data.height
			}).exec();
			// query.select('.btnBox').boundingClientRect(data => {
			// 	this.boxHeight.btnBoxH = data.height
			// }).exec();
			query.select('.textH').boundingClientRect(data => {
				this.boxHeight.textH = data.height
			}).exec();
			
		},
		methods: {
			//详情页返回的时候调用子组件方法刷新列表数据
			async returnData(val) {
				this.$refs.lookRecordRef.paging.pageNum = 1
				this.$refs.lookRecordRef.recordList = await this.$refs.lookRecordRef.getData()
			},
			delItem(index) {
				this.QRcodes.splice(index, 1);
			},
			async changeTab(item) {
				console.debug(item, 'qiehuan')
				this.currentIndex = item.index
				if(item.index === 1) {
					this.$refs.lookRecordRef.paging.pageNum = 1
					this.$refs.lookRecordRef.recordList = await this.$refs.lookRecordRef.getData()
				}
			},
			goBack() {
				uni.navigateBack({})
			},
			fnSure() {
				this.isShowSelect = false
			},
			//提交按钮
			determine() {
				// console.log(this.formData, '点击了按钮');
				if (this.QRcodes.length <= 0) {
					return uni.showToast({
						title: '请先扫描设备二维码',
						icon: 'none'
					})
				}
				let tempObj = this.getLineInfo(this.sectionList)
				const resq = {
					pmId: this.showArr.id,
					projectOrgId:this.showArr.projectOrgId,
					specialTasksSettingId: this.formData.specialTasksSettingId || undefined,
					specialTasksSettingName: this.formData.specialTasksSettingName || undefined,
					workingSurfaceId: this.formData.workingSurfaceId || undefined,
					workingSurfaceName: this.formData.workingSurfaceName || undefined,
					lineId: tempObj.lineId || undefined,
					lineSiteSectionType: tempObj.lineSiteSectionType || undefined,
					lineSiteSectionName: tempObj.lineSiteSectionName || undefined,
					lineName: tempObj.lineName|| undefined,
					lineSiteSectionId: tempObj.lineSiteSectionId || undefined,
					pmBindEqItems: this.QRcodes.map(it => {
						return {
							deviceId: it.deviceId
						}
					}) || undefined,
					code: 'gcwb'
				}
				console.log(resq, '维保接口入参')
				if(this.isLoading) return
				this.isLoading = true
				this.getEquipmentList(resq).then(res => {
					console.log(res,'接口返回的')
					if(res === true) {
						uni.showToast({
							title: '添加成功',
							icon: 'none'
						});
						this.QRcodes = [];
						this.QRcodeData = {};
						this.formData = {}
						this.sectionList = []
						this.showArr = {}
						this.columns = [[],[]]
						this.values = [0,0]
						this.isLoading = false
					}else {
						this.$refs.uToast.show({
							type: 'default',
							message: res,
						})
						this.isLoading = false
					}

				})
			},
			/**
			 * 二维码内容数据必须是json字符串 对象格式{"deviceId":"EQ22110400000803"} 必须得有一个deviceId
			 */
			fnScanCode() {
				if(this.sectionList.length === 0) {
					return uni.showToast({
						title: '请先每日施工计划',
						icon: 'none'
					})
				}
				let self = this;
				// 允许从相机和相册扫码
				uni.scanCode({
					success: async function(res) {
						console.log(res, '结果')
						let result = res.result;
						// 得到deviceId 先做判断 调deviceIsBind方法查询是否绑定
						// 绑定则提示是否换绑
						self.bindData = await self.deviceIsBind(result);
						console.log(self.bindData, '看结果数据');
						self.QRcodeData = self.bindData;
						self.showModal = true;
						self.$nextTick()
					},
					fail(err) {
						console.log(err)
						uni.showToast({
							title: '扫码失败，请确认二维码内容',
							icon: 'none'
						})
					}
				});

			},

			/**
			 * 	批量添加/绑定设备
				@param  {number }  lineId              线路id
				@param  {number }  lineSiteSectionId   站点或者区间id
				lineSiteSectionType站点区间类型
				lineSiteSectionName站点区间名称
				lineName路线名称
				@param  {Array  }  pmBindEqItems       设备列表 对象数组:[{deviceId:number}]
				@return {Promise}  Promise			  异步请求
			 */
			getEquipmentList(obj) {
				return pmBindEqBatchBind(obj).then(res => {
					console.log(res,'批量绑定11');
					if(res.status === 1 && res.success) {
						return true
					}else {
						return res.message
					}
				})
			},
			/**
			 * 查询设备是否绑定
			 * @@param  {String } deviceId 设备id查找绑定数据情况 
			 * @@return {Object } //有值已经绑定  undefined 或者 null 或者 {}则未绑定
			 */
			async deviceIsBind(deviceId) {
				return await new Promise((resolve, reject) => {
					getBindInfoByDeviceId({
						deviceId
					}).then(res => {
						console.log(res.result, 'deviceIsBind接口数据')
						res.result && resolve(res.result) || resolve(undefined)
					}).catch(err => {
						reject(undefined)
					})
				})
			},
			closeModel(str) {
				// console.log(this.QRcodeData, '大')
				switch (str) {
					case 'end': // 确定并结束 
						this.QRcodes.find(it => it.deviceId === this.QRcodeData.deviceId) === undefined && this.QRcodes
							.push(this.QRcodeData)
						break;
					case 'continue':
						this.QRcodes.find(it => it.deviceId === this.QRcodeData.deviceId) === undefined && this.QRcodes
							.push(this.QRcodeData);
						this.fnScanCode();
						break;

				}
				this.showModal = false;
				// 重置绑定数据， 方便下一条数据共用
				this.bindData = {}
			},
			/** 选择施工计划 */
			selectConstructionPlan() {
				uni.navigateTo({ 
				 url: `/subpackage-enginner/pages/engineeringMaintenance/jianKong/constructionPlanList?type=gcwb`,
				 events: {
				 	setData: (data) => {
						this.showArr = data.data
						console.log(this.showArr,' ---')
						this.sectionList = data.data.lineSiteList
				 	}
				 },
				 success: res => {
				 	res.eventChannel.emit('getList', {
				 		data: this.showArr
				 	})
				 }})
			},
			//获取树形数据最后一个list
			extractLowestLevelList(data) {
				let result = [];
				for (let i = 0; i < data.length; i++) {
					if (data[i].list) {
						result = result.concat(this.extractLowestLevelList(data[i].list));
					} else {
						result.push(data[i]);
					}
				}
				return result;
			},
			getLineInfo(tempArray) {
				let obj = {}
				for(const item of tempArray) {
					console.log(item, 'shisha1')
					if(item.list.length > 0) {
						for(const item2 of item.list) {
							if(item2.list.length > 0) {
									obj = {
										lineId: item.id,
										lineName: item.name,
										lineSiteSectionType: item2.id,
										lineSiteSectionId: item2.list[0].id,
										lineSiteSectionName: item2.list[0].name,
									}
							}
						}
					}
				}
				return obj;
			}
		}
	}
</script>

<style lang="scss" scoped>
	.item-list {
		line-height: 50px;
		color: #69717c;
		font-size: 16px;
		> view {
			text-overflow: ellipsis;
			white-space: nowrap;
			overflow: hidden;
			padding: 0 12px 0 26px;
			border-top: 1px solid #eef0f5;
			&:nth-child(1) {
				border-top: none;
			}
		}
	}
	.page-jiankong {
		padding-top: 40rpx;
		background-color: #f5f5f9;
		/* #ifdef MP-WEIXIN */
			padding-top: 200rpx;
		/* #endif */
	}

	.textH {
		padding: 40rpx 0 20rpx 10rpx;
	}

	.top-select {
		background-color: #fff;
		padding: 0 30rpx;

		.sel-name {
			display: flex;
			align-items: center;
			padding: 30rpx 0rpx;
			border-bottom: 1px solid #E2E5ED;
			font-size: 32rpx;
			font-family: PingFang SC-Bold, PingFang SC;
			font-weight: bold;
			color: #445469;
			&:last-of-type{
				border-bottom: none;
			}
			.left-name::before {
				content: "*";
				color: red;
			}

			.left-name {
				width: 200rpx;
			}

			.middle-name {
				flex: 1;
			}
		}
	}

	.top-btn {
		margin-top: 30rpx;
	}

	.item-box {
		background-color: #fff;

		.shebei {
			padding: 15rpx;
			background-color: #fff;
			border-bottom: 1px solid #dededf;
		}

		.box-detail {
			padding: 15rpx;

			.detail-icon {
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding: 6rpx 0;
			}

			.detail-icon.last {
				border-bottom: 1px solid #dededf;
			}
		}
	}

	.btnBox {
		height: 100rpx;

		.btn {
			position: fixed;
			bottom: 0;
			width: 100%;
		}
	}

	.pop-box {
		.title {
			text-align: left;
		}

		.info {
		
			line-height: 64rpx;
		}
	}

</style>
